<?php

namespace app\common\lib\zlcr3;

use app\aliyun\controller\AliyunRtc;
use app\astrologer\lib\AstrPush;
use app\chat\LiveMessage;
use app\common\cachemodel\consult\AppUserConsultGift;
use app\common\cachemodel\OrdersLib;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\User;
use app\zyhsapi\model\ZyhsConfig;
use app\zyhsapi\model\ZyhsConsultAstrData;
use app\zyhsapi\model\ZyhsConsultChatRecord;
use app\zyhsapi\model\ZyhsConsultChatRecordAstr;
use app\zyhsapi\model\ZyhsConsultChatRecordDetails;
use app\zyhsapi\model\ZyhsConsultChatRtcRecord;
use app\zyhsapi\model\ZyhsConsultQuestion;
use app\zyhsapi\model\ZyhsUser;
use app\zyhsapi\model\ZyhsUserAccount;
use think\Db;
use think\Log;
use think\queue\Job;

class RtcConsultJob
{
    /**
     * 发送 连线咨询 问题
     * @param Job $job
     * @param $jobData
     * @return void
     * @throws ApiException
     */
    public function sendConsultQuestion(Job $job, $jobData)
    {
//         $jobData = [
//             'app_type' => 1=>准有好事 2=>准了APP,
//             'uid' =>用户,
//             'id' =>咨询问题ID
//         ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }
        $jobData['app_type'] = (int)($jobData['app_type'] ?? 1);
        // 判断当前是否 已经 提交过了
        $zlcr3ConsultQuestionModel = new ZyhsConsultQuestion();
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $zlcr3ConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
        $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
        try
        {
            $consultQuestionInfo = $zlcr3ConsultQuestionModel->getUserConsultQuestion($jobData['app_type'], $jobData['uid']);
            if (!$consultQuestionInfo || $consultQuestionInfo['id'] !== $jobData['id'] || count($consultQuestionInfo['extend']) >= 5)
            {
                $job->delete();
                return;
            }
            $sendAstro = $consultQuestionInfo['extend']['send_astro'] ?? [];
            // 已发送咨询问题 咨询师
            $sendAstrIds = array_column($sendAstro, 'astr_id');
            // 获取 咨询师 热度榜信息
            $astrHotData = (new ZyhsConsultAstrData())->getRankingList(2);
            foreach ($sendAstrIds as $astrId)
            {   // 删除 已经发送 咨询师数据
                unset($astrHotData[$astrId]);
            }
            $rtcConfig = (new ZyhsConfig())->configInfo('rtc');
            $testUser = $rtcConfig['test_user'] ?? '';
            $testAstrId = explode(',', $testUser);
            foreach ($testAstrId as $value)
            {
                unset($astrHotData[$value]);
            }
            $nowTimw = time();
            $sendNum = count($sendAstrIds); // 已发送咨询师数量
            if ($sendNum >= 5)
            {
                $job->delete();
                return;
            }
            switch ($sendNum)
            {
                case 0:
                case 1:
                    $rNum = 3;
                    break;
                case 2:
                    $rNum = 2;
                    break;
                default:
                    $rNum = 1;
            }
            foreach ($astrHotData as $astrIdItem => $s)
            {
                $ConsultAccount = $zlcr3ConsultAccountModel->getInfoById($astrIdItem, ['status', 'consult_status']);
                if (!$ConsultAccount || $ConsultAccount['status'] !== 1 || $ConsultAccount['consult_status'] !== 1)
                {   // 休息状态 或者 禁止连线  跳过
                    unset($astrHotData[$astrIdItem]);
                }
            }
            $consultAstrIds = $zlcr3ConsultQuestionModel->getSendQuestionAstrIds($astrHotData, $rNum);
            if ($jobData['app_type'] === 1)
            {
                $userInfo = (new ZyhsUser())->getInfoById($jobData['uid']);
            } else
            {
                $userInfo = (new User())->getUserinfo(['id' => $jobData['uid']]);
            }
            $consultQuestionUpdateData = $consultQuestionInfo['extend'];
            $isUpdate = false;
            foreach ($consultAstrIds as $astrId)
            {
                if (in_array($astrId, $sendAstrIds, true))
                {   // 已经发送过， 跳过
                    continue;
                }
                $chatId = $consultChatIdModel->getChatIdByAstrId($jobData['app_type'], $jobData['uid'], $astrId);
                if (!$chatId)
                {
                    $insertData = [
                        'app_type' => $jobData['app_type'],
                        'uid' => $jobData['uid'],
                        'astr_id' => $astrId,
                        'last_chat_detail_id' => 0,
                        'last_chat_detail_time' => 0,
                        'create_time' => $nowTimw,
                    ];
                    // 创建新的会话
                    $chatId = $consultChatIdModel->SaveData($insertData);
                }
                $consultMsgData = [
                    'chat_id' => $chatId,
                    'app_type' => $jobData['app_type'],
                    'uid' => $jobData['uid'],
                    'astr_id' => $astrId,
                    'type' => 2,    //  1=>APP消息 2=>用户发送消息
                    'title' => '',
                    'content' => $consultQuestionInfo['content'], // 提问问题
                    'data_type' => 4,   //  1=>普通消息  2=>图片  3=>语音咨询消息  4=>咨询问题  5=>咨询问题答案
                    'extend' => [
                        'cq_id' => $jobData['id'],
                        'intercept_tips' => $consultQuestionInfo['extend']['intercept_tips'] ?? '',
                    ],  //  语音咨询消息 ｜ 图片信息
                    'pid' => 0, // 待更新
                    'create_time' => $nowTimw,
                ];
                $resData = $consultChatRecordDetailsModel->SaveData($chatId, $consultMsgData);
                if ($resData)
                {
                    $consultChatIdModel->updateData($chatId, [
                        'uid' => $jobData['uid'],
                        'last_chat_detail_id' => $resData['id'],
                        'last_chat_detail_time' => $nowTimw,
                    ], $jobData['app_type']);
                    // 更新咨询师端 最后咨询信息
                    $zlcr3ConsultChatRecordAstrModel->userSendUpdate($jobData['app_type'], $jobData['uid'], $astrId, [
                        'last_chat_detail_id' => $resData['id'],
                        'last_chat_detail_time' => $nowTimw,
                        'user_last_msg_time' => $nowTimw,
                        'unread_num' => Db::raw('unread_num + 1'),
                        'question_num' => Db::raw('question_num + 1'),
                    ]);
                    // 向咨询师 发送信息
                    $astrData = current($consultChatRecordDetailsModel->astrDataListResert([$resData], [], $userInfo, $jobData['app_type']));
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                        'msg_type' => 2,
                        'app_type' => $jobData['app_type'],
                        'uid' => $jobData['uid'],
                        'msg_data' => $astrData,
                    ]);
                    // 咨询问题 更新信息
                    $consultQuestionUpdateData['send_astro'][] = [
                        'astr_id' => $astrId,
                        'answer_id' => 0,
                        'is_read' => 0,
                        'time' => $nowTimw,
                    ];

                    $pushAlert = mb_strlen($consultQuestionInfo['content']) > 25 ? mb_substr($consultQuestionInfo['content'], 0, 25) : $consultQuestionInfo['content'];
                    $pushData = [
                        'action' => 'extend',
                        'target' => 'local',
                        'link' => "chat?id={$userInfo['id']}&app_type={$jobData['app_type']}",
                        'pop_msg' => json_encode([
                            'avatar' => $userInfo['avatar'],
                            'name' => $userInfo['nickname'],
                            'msg' => $pushAlert,
                            'target' => 'local',
                            'link' => "chat?id={$userInfo['id']}&app_type={$jobData['app_type']}",
                            'uid' => $userInfo['id'],
                            'app_type' => $jobData['app_type'],
                        ], JSON_UNESCAPED_UNICODE),
                    ];
                    (new AstrPush())->pushUserMsg($astrId, $pushAlert, $pushData);

                    $sendNum++;
                    $isUpdate = true;
                }
            }
            if ($isUpdate)
            {   // 更新数据
                $zlcr3ConsultQuestionModel->updateData($consultQuestionInfo['id'], $jobData['app_type'], $jobData['uid'], ['extend' => $consultQuestionUpdateData]);
            }
            if ($sendNum >= 5)
            {
                $job->delete();
                return;
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '() 发送 连线咨询 问题 异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }

        // 10分钟后 再次 执行
        $job->delete();
        Util::queuePush('send_consult_question', $jobData, 600);  // 60秒后 扣除准币
    }

    /**
     * 接受连麦 检测  【发起连麦后 2 分钟后 判断状态是否还是待接听 状态 如果是待接听状态 则取消连线】
     * @param Job $job
     * @param $jobData
     * @return void
     * @throws \RedisException
     */
    public function rtcConsultAcceptCheck(Job $job, $jobData)
    {
//        $jobData = [
//            'id' => 咨询问题ID
//        ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        for ($i = 0; $i <= 20; $i++)
        {   // 加锁
            $res = $consultChatRtcRecordModel->setRtcPadlock($jobData['id']);
            if ($res)
            {
                break;
            }
            sleep(1);
        }
        $chatDetail = $consultChatRecordDetailsModel->getInfoById($jobData['id']);
        if (!$chatDetail)
        {
            $job->delete();
            return;
        }
        if (isset($chatDetail['extend']['rtc_data']['rtc_id']) && $chatDetail['extend']['rtc_data']['rtc_id'])
        {   // 已接听
            $job->delete();
            return;
        }
        if ($chatDetail['extend']['rtc_data']['status'] > 1)
        {   // 已挂断
            $job->delete();
            return;
        }
        $appType = $chatDetail['app_type'] ?? 1;
        if ($appType === 1)
        {   // 准有好事
            $websocketWho = LiveMessage::WHO_TYPE_ZYHS_UID;
            $userInfo = (new ZyhsUser())->getInfoById($chatDetail['uid']);
        } else
        {   // 准了APP
            $websocketWho = LiveMessage::WHO_TYPE_UID;
            $userInfo = (new User())->getUserinfo(['id' => $chatDetail['uid']]);
        }
        $rtcData = $chatDetail['extend']['rtc_data'] ?? ['rtc_id' => 0, 'status' => -1];
        $rtcData['status'] = 2;
        $chatDetail['extend']['rtc_data'] = $rtcData;
        // 更新咨询信息状态
        $consultChatRecordDetailsModel->UpdateData($jobData['id'], ['extend' => $chatDetail['extend']]);
        // 咨询师 咨询营业状态 改为休息
        (new Zlcr3ConsultAccount())->updateData($chatDetail['astr_id'], ['status' => 2]);
        // 删除当前连麦 缓存信息
        $userNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(1, $appType, $chatDetail['uid']);
        if ($userNowConsultRtcInfo && $userNowConsultRtcInfo['chat_id'] == $jobData['id'])
        {   // 删除用户当前连麦
            $consultChatRtcRecordModel->delNowRtcDataByCache(1, $appType, $chatDetail['uid'], $userNowConsultRtcInfo['chat_id']);
            // 向用户发送 信息
            // 1 连麦消息
            $popConsultMsg = [
                'msg_type' => 1,
                'astr_id' => $chatDetail['astr_id'],
                'msg_data' => [
                    'id' => $jobData['id'],
                    'type' => 1,
                    'time_des' => '',
                    'time' => '',
                    'avatar' => $userInfo['avatar'],
                    'msg_des' => '连线咨询',
                    'tags' => [],
                    'consult_info' => [
                        'status' => 4, // 1=>申请连线中 2=>连线中 3=>咨询结束
                        'tip' => '咨询师未响应',
                        'target' => 'local',
                        'link' => 'empty',
                    ],
                    'btn_info' => null,
                    'content' => '',
                    'content_type' => 1,
                ],
            ];
            LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $chatDetail['uid']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, $popConsultMsg);
            LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $chatDetail['uid']), LiveMessage::MSG_TYPE_POP_CONSULT_TOAST, [
                'content' => '咨询师暂时不在，稍侯再来吧',
            ]);
        }
        $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $appType, $chatDetail['astr_id']);
        if ($astrNowConsultRtcInfo && $astrNowConsultRtcInfo['chat_id'] == $jobData['id'])
        {   // 删除咨询师当前连麦
            $consultChatRtcRecordModel->delNowRtcDataByCache(2, $appType, $chatDetail['astr_id'], $astrNowConsultRtcInfo['chat_id']);
            // 向咨询师发送 信息
            // 1 连麦消息
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $chatDetail['astr_id']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                'msg_type' => 2,
                'app_type' => $appType,
                'uid' => $chatDetail['uid'],
                'msg_data' => [
                    'id' => $jobData['id'],
                    'type' => 2,
                    'time_des' => '',
                    'time' => '',
                    'avatar' => $userInfo['avatar'],
                    'msg_des' => '连线咨询',
                    'tags' => [],
                    'consult_info' => [
                        'status' => 4, // 1=>申请连线中 2=>连线中 3=>咨询结束
                        'tip' => '咨询师未响应',
                        'target' => 'local',
                        'link' => 'empty',
                    ],
                    'btn_info' => null,
                    'content' => '',
                    'content_type' => 1,
                ],
            ]);
            $voiceCallData = [
                'chat_id' => $jobData['id'],
                'app_type' => $appType,
                'uid' => $chatDetail['uid'],
                'avatar' => $userInfo['avatar'],
                'nickname' => $userInfo['nickname'],
                'status' => 0,
                'desc' => '',
            ];
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $chatDetail['astr_id']), LiveMessage::MSG_TYPE_POP_VOICE_CONSULT_CALL, $voiceCallData);
        }
        if ($appType === 2 && Util::checkAppVersion('2.15.0', $chatDetail['extend']['version'] ?? '1.0.0') !== '小')
        {   // 删除 频道订阅 与 当前RTC房间
            (new AliyunRtc())->rmEventSubAndDelRtcChannel('consult2_' . $jobData['id']);
        }
        $consultChatRtcRecordModel->loseOperatorLicense($jobData['id']);

        $job->delete();
    }

    /**
     * 接受连麦 30秒后判断 是否进入连线中 如果还在连接中 则 取消连线
     * rtc 连接成功检测
     * @param Job $job
     * @param $jobData
     * @return void
     * @throws \RedisException
     */
    public function rtcCunsultClientSucCheck(Job $job, $jobData)
    {
//        $jobData = [
//            'id' => '咨询问题ID',
//            'rtc_id' => '$rtcId',
//        ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        for ($i = 0; $i <= 20; $i++)
        {   // 加锁
            $res = $consultChatRtcRecordModel->setRtcPadlock($jobData['id']);
            if ($res)
            {
                break;
            }
            sleep(1);
        }
        $chatDetail = $consultChatRecordDetailsModel->getInfoById($jobData['id']);
        if (!$chatDetail)
        {
            $job->delete();
            return;
        }
        $rtcId = $jobData['rtc_id'];
        $rtcInfo = $consultChatRtcRecordModel->getInfoById($rtcId);
        if (!$rtcInfo || $rtcInfo['status'] !== 2)  // 1=>待接听  2=>连接中  3=>连麦中 4=>连麦结束 5=>故障挂断 6=>取消连麦（连接中挂断）
        {   // 不在接听中
            $job->delete();
            return;
        }
        $appType = $rtcInfo['app_type'] ?? 1;
        $nowTime = time();
        $rtcInfoUpdate = [
            'type' => 2,
            'end_time' => $nowTime,
            'extend' => $rtcInfo['extend'],
            'duration' => 0,
            'status' => 7,
        ];
        // 获取咨询师 当前连麦状态
        $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $appType, $rtcInfo['astr_id']);
        if ($astrNowConsultRtcInfo && $astrNowConsultRtcInfo['chat_id'] == $chatDetail['id'])
        {   // 咨询师 当前连麦 与当前取消的连麦是一致的
            // 记录 咨询信息
            $rtcInfoUpdate['extend']['recode_datas'] = [];
            $rtcInfoUpdate['extend']['dice_datas'] = [];
            $rtcInfoUpdate['extend']['tarot_datas'] = [];
            // 删除 当前咨询 信息
            $consultChatRtcRecordModel->delNowRtcDataByCache(2, $appType, $rtcInfo['astr_id'], $chatDetail['id']);
        }
        // 更新了连麦状态
        $consultChatRtcRecordModel->updateData($rtcInfo['id'], $appType, $rtcInfo['uid'], $rtcInfoUpdate, 2);
        // 获取用户当前连麦 状态
        $userNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(1, $appType, $rtcInfo['uid']);
        if ($userNowConsultRtcInfo && $userNowConsultRtcInfo['chat_id'] == $chatDetail['id'])
        {   // 用户当前连麦 是 与当前取消是一致的
            $consultChatRtcRecordModel->delNowRtcDataByCache(1, $appType, $rtcInfo['uid'], $chatDetail['id']); // 删除当前连麦信息
        }
        try
        {
            if ($appType === 1)
            {   // 准有好事
                $websocketWho = LiveMessage::WHO_TYPE_ZYHS_UID;
                $userInfo = (new ZyhsUser())->getInfoById($rtcInfo['uid']);
            } else
            {   // 准了APP
                $websocketWho = LiveMessage::WHO_TYPE_UID;
                $userInfo = (new User())->getUserinfo(['id' => $rtcInfo['uid']]);
            }

            if ($appType === 2 && Util::checkAppVersion('2.15.0', $chatDetail['extend']['version'] ?? '1.0.0') !== '小')
            {   // 删除 频道订阅 与 当前RTC房间
                (new AliyunRtc())->rmEventSubAndDelRtcChannel('consult2_' . $jobData['id']);
            } else
            {
                (new AliyunRtc())->rmEventSubAndDelRtcChannel('consult_' . $rtcId);
            }
            $msgData1 = [
                'id' => $chatDetail['id'],
                'type' => 1,
                'time_des' => '',
                'time' => '',
                'avatar' => $userInfo['avatar'],
                'msg_des' => '连线咨询',
                'tags' => [],
                'consult_info' => [
                    'status' => 4,
                    'tip' => '连线已取消',
                    'target' => 'local',
                    'link' => 'empty',
                ],
                'btn_info' => null,
                'content' => '',
                'content_type' => 1,
            ];
            LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $astrNowConsultRtcInfo['uid']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                'msg_type' => 1,
                'astr_id' => $rtcInfo['astr_id'],
                'msg_data' => $msgData1,
            ]);
            LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $chatDetail['uid']), LiveMessage::MSG_TYPE_POP_CONSULT_TOAST, [
                'content' => '接通失败，连线已取消',
            ]);
            $msgData2 = [
                'id' => $chatDetail['id'],
                'type' => 2,
                'time_des' => '',
                'time' => '',
                'avatar' => $userInfo['avatar'],
                'msg_des' => '连线咨询',
                'tags' => [],
                'consult_info' => [
                    'status' => 4,
                    'tip' => '接通失败',
                    'target' => 'local',
                    'link' => 'empty',
                ],
                'btn_info' => null,
                'content' => '',
                'content_type' => 1,
            ];
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $rtcInfo['astr_id']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                'msg_type' => 2,
                'app_type' => $appType,
                'uid' => $rtcInfo['uid'],
                'msg_data' => $msgData2,
            ]);
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $rtcInfo['astr_id']), LiveMessage::MSG_TYPE_POP_CONSULT_TOAST, [
                'content' => '接通失败，连线已取消',
            ]);
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }

        $consultChatRtcRecordModel->loseOperatorLicense($jobData['id']);
        $job->delete();
    }

    /**
     * RTC 连线咨询 准币扣除
     * @param Job $job
     * @param $jobData
     * @throws \Exception
     */
    public function rtcConsultDeductCoin(Job $job, $jobData)
    {
//        $jobData = [
//            'id' => '咨询问题ID',
//        ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 2)
        {   // 失败两次 则删除
            $job->delete();
            return;
        }
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $chatDetail = $consultChatRecordDetailsModel->getInfoById($jobData['id']);
        if (!$chatDetail || !isset($chatDetail['extend']['rtc_data']['rtc_id']) || !$chatDetail['extend']['rtc_data']['rtc_id'])
        {
            $job->delete();
            return;
        }
        $rtcInfo = $consultChatRtcRecordModel->getInfoById($chatDetail['extend']['rtc_data']['rtc_id']);
        if ($rtcInfo['status'] !== 3)
        {   // 咨询状态 不在连线中 队列执行结束
            $job->delete();
            return;
        }
        $appType = $rtcInfo['app_type'] ?? 1;
        if ($appType === 1)
        {   // 准有好事
            $websocketWho = LiveMessage::WHO_TYPE_ZYHS_UID;
            $UserAccountModel = new ZyhsUserAccount();
        } else
        {   // 准了APP
            $websocketWho = LiveMessage::WHO_TYPE_UID;
            $UserAccountModel = new ZhunleUserAccount();
        }
        $nowTime = time();
        $lastDeductTime = $rtcInfo['extend']['last_deduct_time'] ?? $rtcInfo['start_time'];
        if ($nowTime - $lastDeductTime >= 60)
        {   // 获取用户 准币余额
            $userCoin = $UserAccountModel->getUserCoinFromCache($rtcInfo['uid']);  // 账户信息
            $coinNum = (int)($userCoin['balance'] ?? 0);// 准币余额
            // 计算 活动价后 单价金额
            $unitPrice = ceil($rtcInfo['unit_price'] * $rtcInfo['extend']['active_percent']);
            //  获取 连线咨询礼包
            $giftDuration = 0;
            if (isset($rtcInfo['extend']['gift_id']) && $rtcInfo['extend']['gift_id'])
            {   // 当前 连线使用了 礼包
                $userGiftInfo = (new AppUserConsultGift())->getInfoById($rtcInfo['extend']['gift_id']);
                $giftDuration = ($userGiftInfo['duration_minute'] - $userGiftInfo['use_minute']) * 60;  // 礼包连线时长
            }
            //  免费连线处理逻辑开始 -----------------------------------------------------------------------
            $freeRtcDuration = $rtcInfo['extend']['free_rtc_duration'] ?? 0; // 免费连线时长
            $freeRtcDuration = max($freeRtcDuration, $rtcInfo['test_duration']) + $giftDuration;
            if ($freeRtcDuration > $rtcInfo['test_duration'] && $nowTime - $rtcInfo['start_time'] < $freeRtcDuration)
            {   // 免费连线时长大于 试麦时长 && 连线时长 小于 免费连线时长 （还在免费时长的时间之内）
                // ------------- 本次扣费逻辑跳过 -------
                // 剩余免费时长
                $lastFreeRtcDuration = $freeRtcDuration - ($nowTime - $rtcInfo['start_time']);
                // 准币 可连线 分钟数
                $min = floor($userCoin['balance'] / $unitPrice);
                // 剩余最大可连线时长
                $maxDuration = $lastFreeRtcDuration + (int)($min * 60);
                if ($maxDuration < 180 || $lastFreeRtcDuration <= 60)
                {   // 剩余连线时长 不足3分钟
                    $consultDetailRefresh = [
                        'target' => 'local',
                        'link' => "alert_consult_question?id={$jobData['id']}&need_auth=2",
                        'force_open' => 0,
                    ];
                    LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $rtcInfo['uid']), LiveMessage::MSG_TYPE_POP_CONSULT_DETAIL_REFRESH, $consultDetailRefresh);
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $rtcInfo['astr_id']), LiveMessage::MSG_TYPE_POP_CONSULT_DETAIL_REFRESH, $consultDetailRefresh);
                }
                $rtcInfo['extend']['last_deduct_time'] = $lastDeductTime + 60;
                $rtcInfoUpdate = [
                    'extend' => $rtcInfo['extend'],
                ];
                // Update
                $consultChatRtcRecordModel->updateData($rtcInfo['id'], $appType, $rtcInfo['uid'], $rtcInfoUpdate, 1);
                // 计算 下次 结算时间
                $nextDeductTime = $rtcInfo['extend']['last_deduct_time'] + 60 - $nowTime;
                $nextDeductTime = max($nextDeductTime, 0);
                // 重新执行
                Util::queuePush('rtc_consult_deduct_coin', ['id' => $jobData['id']], $nextDeductTime);  // 60秒后 重新执行该队列
                $job->delete();
                //  免费连线处理逻辑结束 -----------------------------------------------------------------------
            } else
            {   // 付费处理逻辑 ---------------------------------------------------------------------------
                $balance2 = $coinNum - $unitPrice;
                $balance3 = $userCoin['balance'] - $unitPrice;
                Log::write("付费处理逻辑JobID:{$jobData['id']} 余额：{$userCoin['balance']} 扣费 {$unitPrice} 准币，剩余 {$balance3} 准币,【逻辑2: {$balance2} 准币】;账号信息：" . json_encode($userCoin, JSON_UNESCAPED_UNICODE) . ";RTC信息：" . json_encode($rtcInfo, JSON_UNESCAPED_UNICODE), 'log');
                if ($coinNum >= $unitPrice)
                {   // 准币足够
                    if (!isset($rtcInfo['extend']['send_sms_time']))
                    {   // 没有发送短信 通知
                        // 开始发送 短信通知
                        if ($appType === 1)
                        {   // 发送 准有好事 短信通知
                            // 146448 【准有好事】您已确认自己为成年人，无精神疾病和自杀倾向，承诺不以任何方式复制、披露、传播用户或平台隐私，违者承担全部法律责任，拒收请回复R
                            $userInfo = (new ZyhsUser())->getInfoById($rtcInfo['uid']);
                            if ($userInfo && isset($userInfo['tel']) && $userInfo['tel'])
                            {
                                Util::sendYxSms2([$userInfo['tel']], '', 146448, [], '【准有好事】');
                            }
                        } else
                        {   // 发送 准了 短信通知
                            // 146450 【准了】您已确认自己为成年人，无精神疾病和自杀倾向，承诺不以任何方式复制、披露、传播用户或平台隐私，违者承担全部法律责任，拒收请回复R
                            $userInfo = (new User())->getUserinfo(['id' => $rtcInfo['uid']]);
                            if ($userInfo && isset($userInfo['tel']) && $userInfo['tel'])
                            {
                                Util::sendYxSms2([$userInfo['tel']], '', 146450, [], '【准了】');
                            }
                        }
                        $rtcInfo['extend']['send_sms_time'] = $nowTime;
                    }
                    $balance = $coinNum - $unitPrice;
                    $consume_price = $userCoin['consume_price'] + OrdersLib::getOrderCoinTotalAmount($unitPrice);
                    $consume_coin = $userCoin['consume_coin'] + $unitPrice;
                    //更新用户钱包金额
                    $UserAccountModel->UpdateData($chatDetail['uid'], ['balance' => $balance, 'consume_price' => $consume_price, 'consume_coin' => $consume_coin, 'update_time' => time()], ['uid' => $chatDetail['uid']]);
                    $rtcInfo['coin'] = $rtcInfo['coin'] + $unitPrice; // 用户消耗准币
                    $rtcInfo['extend']['last_deduct_time'] = $lastDeductTime + 60;
                    $rtcInfoUpdate = [
                        'coin' => $rtcInfo['coin'],
                        'extend' => $rtcInfo['extend'],
                    ];
                    // Update
                    $consultChatRtcRecordModel->updateData($rtcInfo['id'], $appType, $rtcInfo['uid'], $rtcInfoUpdate, 1);
                    if ($balance <= $unitPrice * 3)
                    {   // 准币不足 3分钟 向用户 与 咨询师 发送消息
                        $consultDetailRefresh = [
                            'target' => 'local',
                            'link' => "alert_consult_question?id={$jobData['id']}&need_auth=2",
                            'force_open' => 0,
                        ];
                        LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $rtcInfo['uid']), LiveMessage::MSG_TYPE_POP_CONSULT_DETAIL_REFRESH, $consultDetailRefresh);
                        LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $rtcInfo['astr_id']), LiveMessage::MSG_TYPE_POP_CONSULT_DETAIL_REFRESH, $consultDetailRefresh);
                    }
                    // 计算 下次 结算时间
                    $nextDeductTime = $rtcInfo['extend']['last_deduct_time'] + 60 - $nowTime;
                    $nextDeductTime = max($nextDeductTime, 0);
                    // 重新执行
                    Util::queuePush('rtc_consult_deduct_coin', ['id' => $jobData['id']], $nextDeductTime);  // 60秒后 扣除准币
                    $job->delete();
                } else
                {   // 准币不足
                    // 挂断   咨询师 结算
                    Log::write("结算处理逻辑JobID:{$jobData['id']} 余额：{$userCoin['balance']} 扣费 {$unitPrice} 准币,【逻辑2: {$balance2} 准币】;账号信息：" . json_encode($userCoin, JSON_UNESCAPED_UNICODE) . ";RTC信息：" . json_encode($rtcInfo, JSON_UNESCAPED_UNICODE), 'log');
                    $consultChatRtcRecordModel->rtcConsultHangUp($chatDetail, '', 1, 3);
                    if ($appType === 2 && Util::checkAppVersion('2.15.0', $chatDetail['extend']['version'] ?? '1.0.0') !== '小')
                    {   // 删除 频道订阅 与 当前RTC房间
                        (new AliyunRtc())->rmEventSubAndDelRtcChannel('consult2_' . $jobData['id']);
                    } else
                    {
                        (new AliyunRtc())->rmEventSubAndDelRtcChannel('consult_' . $rtcInfo['id']);
                    }
                    $job->delete();
                    return;
                }
            }
        } else
        {   // 未到扣费时间
            Util::queuePush('rtc_consult_deduct_coin', ['id' => $jobData['id']], 60 - ($nowTime - $lastDeductTime));  // 60秒后 扣除准币
            $job->delete();
        }
    }
}
